package com.aos.erp.fs.storage.handler;

import com.aliyun.oss.OSSClient;
import com.aos.erp.common.utils.DateUtils;
import com.aos.erp.fs.enums.FileUriType;
import com.aos.erp.fs.model.SysFile;
import com.aos.erp.fs.storage.FileStorageHandler;
import com.aos.erp.fs.storage.StorageConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
@Component
public class AliOSSStorageHandler implements FileStorageHandler {

    @Value("${ali.oss.endPoint:}")
    private String endPoint = "";
    @Value("${ali.oss.keyId:}")
    private String keyId = "";
    @Value("${ali.oss.keySecret:}")
    private String keySecret = "";
    @Value("${ali.oss.bucketName:}")
    private String bucketName = "";

    @Override
    public boolean save(SysFile sysFile, MultipartFile file, String type) {

        //todo 调用接口存储

        String exName = getExName(file.getOriginalFilename());

        String objectName = makeFilePath(sysFile.getAppId(), "erp", "n_" + DateUtils.getXXTimeString() + RandomStringUtils.randomNumeric(4) + exName);

        OSSClient ossClient = new OSSClient(this.endPoint, this.keyId, this.keySecret);
        try {
            ossClient.putObject(this.bucketName, objectName, file.getInputStream());

            sysFile.setUriSrc(objectName);
            sysFile.setUriType(FileUriType.aliOSS);
            return true;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            ossClient.shutdown();
        }

        return false;
    }


    private String makeFilePath(String appId, String bizType, String fileName) {
        String path = getStoragePath(appId, bizType);
        path = path + File.separator + fileName;
        return path;
    }

    public static String getExName(String name) {
        int i = name.lastIndexOf(".");
        if (i > 0) {
            return name.substring(i);
        }
        return "";
    }


    @Override
    public boolean canHandler(SysFile sysFile, MultipartFile file, String type) {
        return StorageConstants.ALI_OSS.equalsIgnoreCase(type);
    }
}
